833. 字符串中的查找与替换
为保证权益,题目请参考 833. 字符串中的查找与替换(From LeetCode).
解决方案1
CPP
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
string findReplaceString(string s, vector<int> &indices, vector<string> &sources, vector<string> &targets)
{
string ans = "";
vector<int> idxs(indices.size(), 0);
for (int i = 0; i < indices.size(); i++)
{
idxs[i] = i;
}
sort(idxs.begin(), idxs.end(), [&](int a, int b) { return indices[a] < indices[b]; });
int sidx = 0;
int iidx = 0;
while (sidx < s.size())
{
if (iidx < idxs.size())
{
bool findGoodOne = false;
while (iidx < idxs.size() && indices[idxs[iidx]] == sidx)
{
if (s.substr(indices[idxs[iidx]], sources[idxs[iidx]].size()) == sources[idxs[iidx]])
{
findGoodOne = true;
ans += targets[idxs[iidx]];
sidx += sources[idxs[iidx]].size();
iidx += 1;
break;
}
iidx += 1;
}
if (!findGoodOne)
{
ans += s[sidx];
sidx += 1;
}
}
else
{
ans += s[sidx];
sidx += 1;
}
}
return ans;
}
};
int main()
{
Solution so;
vector<int> indices = {3, 5, 1};
vector<string> sources = {"kg", "ggq", "mo"};
vector<string> targets = {"s", "so", "bfr"};
cout << so.findReplaceString("vmokgggqzp", indices, sources, targets) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75